﻿using System;
using System.Diagnostics.Contracts;
using System.Dynamic;
using Isuka.Reflection;

namespace Isuka.Excel.Dynamic
{
    internal class DynamicUtility
    {

        public static bool AssignValue<TBinder>(TBinder binder, out object result, Func<TBinder, object> value)
            where TBinder : DynamicMetaObjectBinder
        {
            Contract.Requires(value != null);
            Contract.Assume(binder != null);
            return AssignValue(binder, out result, value(binder));
        }

        public static bool AssignValue(DynamicMetaObjectBinder binder, out object result, object value)
        {
            Contract.Assume(binder != null);
            Contract.Assume(binder.ReturnType != null);
            try
            {
                var returnType = binder.ReturnType;

                if (value == null)
                {
                    result = returnType.IsValueType ? TypeHelper.GetDefaultOf(returnType) : null;
                    return true;
                }
                else
                {
                    // ReturnType ってあまり意味ない？
                    //result = Convert.ChangeType(value, returnType);
                    result = value;
                    return true;
                }
            }
            catch (Exception)
            {
                result = null;
                return false;
            }
        }
    }
}
